package cn.orange.ch03_linked;

import cn.orange.ListNode;

/**
 * LC206.反转链表
 给你单链表的头节点 head ，请你反转链表，并返回反转后的链表
 */
public class LC206 {
    public ListNode reverseListD(ListNode head) { //迭代解法
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode nxt = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nxt;
        }
        return prev;
    }
    public ListNode reverseList(ListNode head) { //递归解法
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
    public static void main(String[] args) {
        LC206 alg = new LC206();
        ListNode h1 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, new ListNode(6))))));
        System.out.println(alg.reverseListD(h1));
        ListNode h2 = new ListNode(1, new ListNode(2, new ListNode(3)));
        System.out.println(alg.reverseListD(h2));
    }
}
